package com.yikaiye.android.yikaiye.ui.activity;

import android.text.TextUtils;

import androidx.activity.OnBackPressedCallback;
import androidx.activity.OnBackPressedDispatcher;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.base.BaseActivity;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.ActivityMainBinding;
import com.yikaiye.android.yikaiye.dialog.DownloadDialog;
import com.yikaiye.android.yikaiye.dialog.MyDialog;
import com.yikaiye.android.yikaiye.dialog.OrderDialog;
import com.yikaiye.android.yikaiye.model.OrderProductModel;
import com.yikaiye.android.yikaiye.ui.activity.viewmodel.MainViewModel;
import com.yikaiye.android.yikaiye.ui.fragment.IndexFragment;
import com.yikaiye.android.yikaiye.ui.fragment.MineFragment;
import com.yikaiye.android.yikaiye.ui.fragment.OrderFragment;
import com.yikaiye.android.yikaiye.ui.fragment.ServiceFragment;
import com.yikaiye.android.yikaiye.utils.AppUtils;
import com.yikaiye.android.yikaiye.utils.CommonUtil;
import com.yikaiye.android.yikaiye.utils.DownLoadHelper;
import com.yikaiye.android.yikaiye.utils.ToastHelper;
import com.yikaiye.android.yikaiye.utils.UMengUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity<ActivityMainBinding, MainViewModel> {

    private long lastPressBackKeyTime = 0;
    private String[] tabTitles;
    private final int[] selectIcons = {R.mipmap.tab_bar_1_1, R.mipmap.tab_bar_2_1, R.mipmap.tab_bar_3_1, R.mipmap.tab_bar_5_1};
    private final int[] normalIcons = {R.mipmap.tab_bar_1, R.mipmap.tab_bar_2, R.mipmap.tab_bar_3, R.mipmap.tab_bar_5};
    private final ArrayList<Fragment> fragments = new ArrayList<>();
    private MyDialog myDialog;
    private String downApkUrl;
    private final OnBackPressedDispatcher onBackPressedDispatcher = getOnBackPressedDispatcher();

    @Override
    protected MainViewModel bindModel() {
        return getViewModel(this, MainViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initData() {
        requestTranslucentStatusBar(false);
        tabTitles = new String[]{getString(R.string.tab_home), getString(R.string.tab_order), getString(R.string.tab_service), getString(R.string.tab_mine)};
        initFragment();
        initDialog();
        viewModel.checkVersion();
        viewModel.getOrderList();

        // 注册返回键处理逻辑
        onBackPressedDispatcher.addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                // 在这里处理返回键的行为
                // 可以调用 super.onBackPressed() 来执行默认的返回行为
                if (System.currentTimeMillis() - lastPressBackKeyTime < 1500) {
                    finish();
                } else {
                    lastPressBackKeyTime = System.currentTimeMillis();
                    ToastHelper.show(getString(R.string.exit_app));
                }
            }
        });
    }

    @Override
    protected void initClick() {
        // 版本更新
        viewModel.versionModelMutableLiveData.observe(this, versionModel -> {
            int currentVersion = Integer.parseInt(AppUtils.getVersionName(context).replace(".", ""));
            int serviceVersion = Integer.parseInt(versionModel.getVersion().replace(".", ""));
            if (currentVersion < serviceVersion) {
                downApkUrl = versionModel.getDownYkyAppUrl();
                myDialog.showDialog();
            }
        });

        // 预订单
        viewModel.orderDataModelMutableLiveData.observe(this, orderDataModel -> {
            List<OrderProductModel> records = orderDataModel.getRecords();
            if (records != null && !records.isEmpty()) {
                OrderProductModel orderProductModel = records.get(0);
                showOrderDialog(orderProductModel);
            }
        });
    }

    private void showOrderDialog(OrderProductModel orderProductModel) {
        OrderDialog orderDialog = new OrderDialog(this, orderProductModel);
        orderDialog.showDialog();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Constant.isFromPay) {
            binding.navigationBar.selectTab(1, false);
        }
    }

    private void initFragment() {
        fragments.add(new IndexFragment());
        fragments.add(new OrderFragment());
        fragments.add(new ServiceFragment());
        fragments.add(new MineFragment());
        binding.navigationBar.titleItems(tabTitles).fragmentList(fragments).normalIconItems(normalIcons).selectIconItems(selectIcons).fragmentManager(getSupportFragmentManager()).tabTextSize(12).setPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        UMengUtil.setCountEventId(Constant.BOTTOM_BAR_HOME);
                        break;
                    case 1:
                        UMengUtil.setCountEventId(Constant.BOTTOM_BAR_ORDER);
                        break;
                    case 2:
//                        UMengUtil.setCountEventId(Constant.BOTTOM_BAR_ORDER);
                        break;
                    case 3:
                        UMengUtil.setCountEventId(Constant.BOTTOM_BAR_MINE);
                        break;
                }
                requestTranslucentStatusBar(position != 0);
                viewModel.getOrderList();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        }).build();
    }

    private void initDialog() {
        myDialog = new MyDialog(this) {
            @Override
            public void leftClick() {
                dismissDialog();
            }

            @Override
            public void rightClick() {
                if (!TextUtils.isEmpty(downApkUrl)) {
                    downloadApk(downApkUrl);
                }
                dismissDialog();
            }
        };
        myDialog.setText(getString(R.string.version_update), getString(R.string.update_to_last_version_), getString(R.string.cancel_text), getString(R.string.confirm_text));
    }

    /**
     * 通过链接下载apk进行更新
     *
     * @param apkUrl apk下载链接
     */
    private void downloadApk(String apkUrl) {
        // 截取apk的名称，如yky.apk
        String destFileName = apkUrl.substring(apkUrl.lastIndexOf("/") + 1);
        final File filesDir = getExternalFilesDir("upgrade");
        // 如果文件不存在新建一个
        if (filesDir != null) {
            if (!filesDir.exists()) {
                filesDir.mkdirs();
            }

            final String filePath = filesDir.getPath() + "/";
            DownloadDialog downloadDialog = new DownloadDialog(this);
            downloadDialog.showDialog();
            DownLoadHelper.getInstance().download(apkUrl, filePath, new DownLoadHelper.OnDownloadListener() {
                @Override
                public void onDownloadSuccess(String path) {
                    downloadDialog.dismissDialog();
                    if (!XXPermissions.isGrantedPermission(context, Permission.REQUEST_INSTALL_PACKAGES)) {
                        XXPermissions.with(context).permission(Permission.REQUEST_INSTALL_PACKAGES).request((permissions, all) -> CommonUtil.installAPK(context, filePath + destFileName));
                    } else {
                        CommonUtil.installAPK(context, filePath + destFileName);
                    }
                }

                @Override
                public void onDownloading(int progress) {
                    downloadDialog.setProgress(progress);
                }

                @Override
                public void onDownloadFailed() {
                    downloadDialog.dismissDialog();
                }
            });
        }
    }
}